package cn.tjnext.apply.web.controller;

import cn.tjnext.apply.contants.BaseModelAttributeNames;
import cn.tjnext.apply.contants.PagePaths;
import cn.tjnext.apply.contants.ProductConstants;
import cn.tjnext.apply.contants.RequestMappingPaths;
import cn.tjnext.apply.dao.UserDao;
import cn.tjnext.apply.entity.ApplicantEntity;
import cn.tjnext.apply.entity.UserEntity;
import cn.tjnext.apply.repositories.UserRepository;
import cn.tjnext.apply.service.AbstractService;
import cn.tjnext.apply.service.ApplicantService;
import cn.tjnext.apply.service.UserService;
import cn.tjnext.apply.utils.EncryptHelper;
import cn.tjnext.apply.web.model.*;
import com.fasterxml.jackson.databind.jsonFormatVisitors.JsonArrayFormatVisitor;
import com.fasterxml.jackson.databind.util.JSONPObject;
import jdk.nashorn.internal.parser.JSONParser;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.ArrayList;
import java.util.Date;
import java.util.Enumeration;
import java.util.List;

/**
 * 移动端页面
 * Created by cp on 2017/7/31.
 */
@Component
@Controller
@RequestMapping(RequestMappingPaths.APP)
public class AppController extends AbstractController<UserEntity, UserRepository, UserDao>{

    @Value("${MERCHANTID}")
    private String MERCHANTID;
    @Value("${POSID}")
    private String POSID;
    @Value("${BRANCHID}")
    private String BRANCHID;
    @Value("${CURCODE}")
    private String CURCODE;
    @Value("${TXCODE}")
    private String TXCODE;
    @Value("${TYPE}")
    private String TYPE;
    @Value("${PUB}")
    private String PUB;
    @Value("${GATEWAY}")
    private String GATEWAY;
    @Value("${THIRDAPPINFO}")
    private String THIRDAPPINFO;
    @Value("${CCBURL}")
    private String CCBURL;

    @Autowired
    private UserService userService;
    @Autowired
    private ApplicantService applicantService;

    /**
     * 注册页
     * @return
     */
    @RequestMapping(value = RequestMappingPaths.REGISTER, method = RequestMethod.GET)
    public String toRegister() {
        return PagePaths.APP + PagePaths.REGISTER;
    }

//    /**
//     * 登录页
//     * @return
//     */
//    @RequestMapping(value = RequestMappingPaths.LOGIN)
//    public String toLogin() {
//        return PagePaths.APP + PagePaths.LOGIN;
//    }

//    /**
//     * 报名页
//     * @return
//     */
//    @RequestMapping(value = RequestMappingPaths.SIGN, method = RequestMethod.GET)
//    public String toSign(Long id, Model model, HttpServletRequest request) {
//        Enumeration enu = request.getHeaderNames();
//        UserEntity userEntity = userService.findOne(id);
//        model.addAttribute(BaseModelAttributeNames.USER, userEntity);
//        List<ApplicantEntity> applicants = applicantService.findByUserId(userEntity.getPkId());
//        model.addAttribute(BaseModelAttributeNames.APPLICANTS, applicants);
//        return PagePaths.APP + PagePaths.SIGN;
//    }
    /**
     * 报名页
     * @return
     */
    @RequestMapping(value = RequestMappingPaths.LOGIN)
    public String toSign(Model model, HttpServletRequest request) {
        model.addAttribute(BaseModelAttributeNames.DATA_LIST, ProductConstants.getProductList);
        return PagePaths.APP + PagePaths.SIGN;
    }
    /**
     * 报名页
     * @return
     */
    @RequestMapping(value = RequestMappingPaths.WRITESIGN, method = RequestMethod.POST)
    public String toWriteSign(String way, String userDetails, Model model, HttpServletRequest request) {
        List<UserDetailModel> userDetailModels = new ArrayList<>();
        JSONArray jsonArray = JSONArray.fromObject(userDetails);
        for (int i = 0; i < jsonArray.size(); i++) {
            JSONObject jsonObject= (JSONObject) jsonArray.get(i);
            userDetailModels.add(new UserDetailModel(jsonObject.optString("id"), jsonObject.optString("name"), jsonObject.optString("price"), jsonObject.optLong("number")));
        }
        DetailModel detailModel = new DetailModel();
        detailModel.setProductId(way);
        detailModel.setUserDetails(userDetailModels);
        model.addAttribute(BaseModelAttributeNames.DATA, detailModel);
        return PagePaths.APP + PagePaths.WRITESIGN;
    }

    /**
     * 级联获取选中线路的详细价格
     * @param id 线路id
     * @return
     */
    @GetMapping(value = RequestMappingPaths.DETAILS + RequestMappingPaths.ID)
    public String getProductDetail(@PathVariable String id, Model model) {
        model.addAttribute(BaseModelAttributeNames.DATA_LIST, ProductConstants.productMap.get(id));
        return getBasePath() + "/detail";
    }

    /**
     * 注册完成
     * @param userEntity
     * @param response
     */
    @ResponseBody
    @RequestMapping(value = RequestMappingPaths.REGISTER_LOGIN, method = RequestMethod.POST,
            consumes = MediaType.APPLICATION_JSON_UTF8_VALUE, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public BaseModel toRegister(@RequestBody UserEntity userEntity, HttpServletResponse response) {
        userEntity.setCreateTime(new Date());
        String MD5Password = null;
        try {
            MD5Password = EncryptHelper.encodeMD5(userEntity.getPassword());
        } catch (Exception e) {
            new BaseModel("密码编码失败");
        }
        userEntity.setPassword(MD5Password);
        return saveImpl(userEntity);
    }

    /**
     * 登录
     * @param userEntity
     * @return
     */
    @ResponseBody
    @RequestMapping(value = RequestMappingPaths.LOGIN_SIGN, method = RequestMethod.POST,
            consumes = MediaType.APPLICATION_JSON_UTF8_VALUE, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public CheckLoginModel toLogin(@RequestBody UserEntity userEntity, HttpSession session) {
        CheckLoginModel checkLoginModel = userService.checkPassword(userEntity.getPhone(), userEntity.getPassword());
        if (StringUtils.isEmpty(checkLoginModel.getErrorMessage())){
            session.setAttribute("user", checkLoginModel);
        }
        return checkLoginModel;
    }

    /**
     * 报名
     * @param applicantEntities
     * @param response
     * @return
     */
    @ResponseBody
    @RequestMapping(value = RequestMappingPaths.SIGN_PAY, method = RequestMethod.POST,
            consumes = MediaType.APPLICATION_JSON_UTF8_VALUE, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public SignModel sign(@RequestBody List<ApplicantEntity> applicantEntities, HttpServletResponse response) {
        SignModel signModel = new SignModel();
        Double orderPrice = 0D;
        // 生成订单id
        Long orderId = System.currentTimeMillis() % 100000000;
        List<ApplicantEntity> applicants = applicantService.findByOrderId(orderId);
        while (applicants.size() > 0) {
            orderId = System.currentTimeMillis() % 100000000;
        }
        for (ApplicantEntity applicantEntity : applicantEntities) {
            applicantEntity.setCreateTime(new Date());
            applicantEntity.setOrderId(orderId);
            orderPrice += Double.parseDouble(applicantEntity.getTypePrice());
            try {
                applicantService.createOrSave(applicantEntity);
            } catch (Exception e) {
                return new SignModel(e.getMessage());
            }
        }
        PayModel payModel = new PayModel(MERCHANTID, POSID, BRANCHID, orderPrice.toString(), CURCODE, TXCODE, TYPE, PUB, GATEWAY, THIRDAPPINFO, CCBURL, orderId);
        signModel.setPayModel(payModel);
        return signModel;
    }

    /**
     * 验证注册手机号是否已注册
     * @param data
     * @return
     */
    @ResponseBody
    @RequestMapping(value = RequestMappingPaths.CHECK)
    public boolean check(String data) {
        return userService.checkLoginPhone(data);
    }

    /**
     * 验证注册手机号是否已注册
     * @param data
     * @return
     */
    @ResponseBody
    @RequestMapping(value = RequestMappingPaths.CHECK + RequestMappingPaths.LOGIN,method = RequestMethod.POST)
    public boolean checkLogin(String data) {
        return !userService.checkLoginPhone(data);
    }

    @Override
    protected UserEntity getNewEntity() {
        return new UserEntity();
    }

    @Override
    protected GenericEntityModel<UserEntity> createEntityModel(UserEntity entity) {
        return null;
    }

    @Override
    protected String getBasePath() {
        return PagePaths.APP;
    }

    @Override
    protected AbstractService<UserEntity, UserRepository, UserDao> getService() {
        return userService;
    }
}
